<?php

namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Schema;
require base_path('vendor').'/qiniu/php-sdk/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class ApiController extends BaseController
{
    const ERROR_CODE = 400; //一般错误code
    const SUC_CODE = 200; //请求成功code
    const UN_BIND_OPENID = 4400; //未绑定open_id需要跳转授权绑定
    public $type = [
        '1' => '商品订单',
        '2' => '充值订单',
        '3' => '代充值订单',
    ];

    public function __construct()
    {
        error_reporting(E_ERROR);

    }

    /**
     * @param null $data
     * @param string $ret
     * @param string $msg
     * @return mixed
     * @throws \ErrorException
     */

    public static function response($data = null,$ret='200',$msg='操作成功')
    {
        if (!empty($data)&&!is_object($data)&&!is_array($data)){
            throw new  \ErrorException('data类型错误');
        }
        if (empty($data)) {
            if (is_object($data)){
                $res =  ['ret'=>intval($ret),'msg'=>$msg,'data'=>new \stdClass()];
            }else{
                $res =  ['ret'=>intval($ret),'msg'=>$msg,'data'=>[]];
            }

        } else {
            $res =  ['ret'=>intval($ret),'msg'=>$msg,'data'=>$data];
        }
        if (!empty($res['data']) && is_array($res['data'])) {
            foreach ($res['data'] as  &$val) {
                if ( is_numeric ( $val ) ) {
                    $val = strval($val);
                }
                if (is_null($val)) {
                    $val = '';
                }
                if (is_array ($val)) {
                    $val = self::changeString($val);
                }
            }
        }

        //支持validator和messageBag
        if($res['msg'] instanceof \Illuminate\Validation\Validator){
            $res['msg'] =  $res['msg']->errors()->first();
        }else if($res['msg'] instanceof \Illuminate\Support\MessageBag){
            $res['msg'] =  $res['msg']->first();
        }

        return response(json_encode($res,JSON_UNESCAPED_UNICODE))
            ->header('Content-Type', 'application/json')
            ->header('Charset','UTF-8')
            ->header('Access-Control-Allow-Credentials', 'false');
    }

    public static function changeString($array)
    {
        foreach ($array as  $key=>$val) {
            if ( is_numeric ( $val ) ) {
                $array[$key] = strval($val);
            }
            if (is_null($val)) {
                $array[$key] = '';
            }
            if (is_array($val)){
                $array[$key] = self::changeString($val);
            }
        }
        return $array;
    }


    public static function Token(){
        $str = md5(uniqid(md5(microtime(true)),true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }


    public static function mkPass($user_password,int $user_salt)
    {
        $password = md5( $user_password .$user_salt);
        return $password;
    }


    public static function http_json($params,$url)
    {
        if (empty($url)){
            throw new \Error('URL为空');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_POST,           1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($params));// 必须为字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain'));// 必须声明请求头
        $return = curl_exec($ch);
        return $return;
    }


    /**
     * 生成订单号
     * @param int $type 1 商品订单 2 充值订单 3 代充值订单
     * @return string
     */
    public static function get_order_sn(int $type):string {

        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[(intval(date('Y')) - 2011) % 10] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn."_V".$type;
    }



    /**
     * 时间轴函数, Unix 时间戳
     * @param int $time 时间
     */
    public static function TranTime($time) {
        //$time = strtotime($time);
        $nowTime = time ();
        $message = '';
        //一年前
        if (idate ( 'Y', $nowTime ) != idate ( 'Y', $time )) {

            if ((date('m',$nowTime)==date('m',$time))&&(date('m',$nowTime)==date('m',$time))) {
                $message = date ( 'Y年', $time ).'的今天';
            }else{
                $message = date ( 'Y年m月d日', $time );
            }
        }
        else {
            //同一年
            $days = idate ( 'z', $nowTime ) - idate ( 'z', $time );
            switch(true){
                //一天内
                case (0 == $days):
                    $seconds = $nowTime - $time;
                    //一小时内
                    if ($seconds < 3600) {
                        //一分钟内
                        if ($seconds < 60) {
                            if (3 > $seconds) {
                                $message = '刚刚';
                                break;
                            } else {
                                $message = $seconds . '秒前';
                                break;
                            }
                        }
                        $message = intval ( $seconds / 60 ) . '分钟前';
                        break;
                    }
                    $message = idate ( 'H', $nowTime ) - idate ( 'H', $time ) . '小时前';
                    break;
                //昨天
                case (1 == $days):
                    $message = '昨天' . date ( 'H:i', $time );
                    break;
                //前天
                case (2 == $days):
                    $message = '前天 ' . date ( 'H:i', $time );
                    break;
                //7天内
                case (7 > $days):
                    $message = $days . '天前';
                    break;
                //超过7天
                default:
                    $message = date (  'n月j日 H:i', $time );
                    break;
            }
        }
        return $message;
    }

    /**
     * @param $str
     * @return bool/array
     */
    public static function getApiData($str):string
    {
        $data = Redis::get('api:'.$str);
        $data = ''; //暂时都清楚缓存
        if (!$data){
            return '';
        }
        return $data;
    }

    #过滤数据库中不存在的键
    public static function createData($table,$data)
    {
        $res                   = [];
        $colums               = Schema::getColumnListing($table);
        foreach ($data as $k =>$v){
            if (in_array($k,$colums)){
                $res[$k]      = $v;
            }
        }
        return $res;
    }


    public static function uploadToken()
    {
        $accessKey = 'HKkqE7UxJijn_mlMJUeSCU7yBCGEuO9LbG3bV-O7';
        $secretKey = '5I6yguRK4pMp8Cn0X5HQ3dICSrBFbDwGKqD9hj4M';
        $auth = new Auth($accessKey, $secretKey);
        $bucket = 'shop';
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        return $token;
    }

    /**
     * 服务器端直传文件到七牛云
     */
    public static function uploadQiuniu($filePath,$url='http://pdgccdat2.bkt.clouddn.com/')
    {
        $token = self::uploadToken();
        // 上传到七牛后保存的文件名
        $key = null;
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            return $url.$ret['key'];
        }
    }


    public static function getOrderType(string $order_sn)
    {
        $suffix = explode('_',$order_sn)[1];
        $type   = trim($suffix,'V');
        return $type;
    }


}
